'use strict';

let debug = require('debug')('shop');
let mongoDao = new require('./mongo/Ware.js')();
let shopDispatcher = require('./shop.js');
let cateDispatcher = require('./category.js');
let fout = require('../common/function.js').formatOutput;

let DaoDispatcher = function () {
};
module.exports = new DaoDispatcher();

let theProto = DaoDispatcher.prototype;

/**
 * 添加单个,从商铺获取消息,填充到商品
 {
    "name":"xx",
    "cates":["美容","美发"],
    "shopIds":["133","112"],
    "imgUrl": ["https://www.baidu.com/img/bdlogo.png"],
    "price":123,
    "priceMarket":999
 }
 * @param inParams
 * @returns {*}
 */
theProto.addOne = function*(inParams) {
    let shopIds = inParams.shopIds;
    let cates = inParams.cates;

    // check cates exists
    let cateCheck = yield cateDispatcher.exists(cates);
    let cr = cateCheck.result;
    for (var key in cr) {
        if (!cr[key]) {
            return fout(10501, 'cate not exits:' + key);
        }
    }

    // update shops
    let tmp = yield shopDispatcher.updateCates(shopIds, cates);
    if (tmp.errCode !== 0) {
        return tmp;
    }

    // update ware info from the shop
    let shops = yield shopDispatcher.findByIdList(shopIds);
    if (shops.errCode !== 0) {
        return shops; // error info
    }
    shops = shops.result;

    for (let i = 0; i < shopIds.length; i++) {
        // find the shop
        let shop = null;
        let sId = shopIds[i];
        for (let j = 0; j < shops.length; j++) {
            if (shops[j]._id.toString() === sId) {
                shop = shops[j];
                break;
            }
        }
        if (shop === null) {
            continue;
        }

        let aWare = {
            name: inParams.name,
            cates: inParams.cates,
            districts: shop.districts,
            loc: shop.loc,
            price: inParams.price,
            priceMarket: inParams.priceMarket,
            shopId: shop._id
        };
        let t = yield mongoDao.save(aWare);
        if (t.errCode !== 0) {
            return t;
        }
    }

    return fout(0, null, 'save wares ok');
};
